import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:shimmer/shimmer.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import 'package:sports_new/widgets/ladder_tab_bar.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:sports_new/widgets/loading/shimmer_loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../controller/record/hot_channel_logic.dart';
import '../../entity/record/channel_entity.dart';
import '../../entity/record/recent_channel_entity.dart';
import '../../resources/colours.dart';
import '../../resources/styles.dart';
import '../../utils/utils.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/base/qkd_dialog.dart';

class HotChannelPage extends StatefulWidget {
  const HotChannelPage({super.key, this.type});

  final int? type;

  @override
  State<HotChannelPage> createState() => _HotChannelPageState();
}

class _HotChannelPageState extends State<HotChannelPage> {
  late final logic = Get.put(HotChannelLogic(),tag: "${widget.type}");

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HotChannelLogic>(
      tag: "${widget.type}",
      initState: (state){
        if(widget.type != null) logic.channelType = widget.type!;
      },
      builder: (logic) => VisibilityDetector(
        key: const Key("hotChannel"),
        onVisibilityChanged: (VisibilityInfo info) {
          if(!info.visibleBounds.isEmpty){
            update();
          }
        },
        child: Scaffold(
          body: SliverViewObserver(
            controller: logic.contentController,
            sliverContexts: () => [
              if(logic.listContext != null) logic.listContext!
            ],
            onObserveAll: (result) => {
              result.forEach((key, value) {
                if(key == logic.listContext){
                  final model = value as ListViewObserveModel;
                  logic.observerList(model);
                }
              })
            },
            child: EasyRefresh.builder(
              controller: logic.refreshController,
              scrollController: logic.scrollController,
              onRefresh: logic.getRecent,
              header: Styles.refreshHeader(position: IndicatorPosition.locator,clamping: true),
              childBuilder: (context,physics) {
                return ExtendedNestedScrollView(
                  physics: physics,
                  controller: logic.scrollController,
                  headerSliverBuilder: (context, innerBoxIsScrolled) => [
                    const HeaderLocator.sliver(clearExtent: false),
                    SliverToBoxAdapter(child: top()),
                  ],
                  body: Builder(
                    builder: (context) {
                      final innerScrollController = PrimaryScrollController.of(context);
                      if(innerScrollController != logic.bodyController){
                        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                          logic.bodyController = innerScrollController;
                        });
                      }
                      return Column(
                        children: [
                          LoadingWidget<bool>(
                            isLoading: logic.areas == null,
                            loading: shimmerArea(),
                            data: logic.areas?.length == 0,
                            child: () => _areaBar()
                          ),
                          Expanded(
                            child: Row(
                              children: [
                                LoadingWidget<bool>(
                                  isLoading: logic.areas == null,
                                  loading: shimmerLeft(),
                                  data: logic.area?.list?.length == 0,
                                  child: () => _leftList()
                                ),
                                Expanded(
                                  child: LoadingWidget<bool>(
                                    isLoading: logic.areas == null,
                                    loading: shimmerList(physics),
                                    data: logic.area?.list?.length == 0,
                                    child: () => _contentList(physics)
                                  )
                                )
                              ],
                            )
                          )
                        ],
                      );
                    }
                  )
                );
              }
            ),
          ),
        ),
      ),
    );
  }

  Widget _areaBar() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      height: 44,
      child: ListView(
        clipBehavior: Clip.none,
        scrollDirection: Axis.horizontal,
        children: [
          ...logic.areas?.map((e) => Container(
            margin: const EdgeInsets.only(right: 10),
            alignment: Alignment.center,
            child: Container(
              width: 60,
              height: 24,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                border: Border.all(
                  color: e.area == logic.area?.area
                    ? Colours.main : Colours.grey666666
                ),
                borderRadius: BorderRadius.circular(12)
              ),
              child: QkdText(
                "${e.area}",
                color: e.area == logic.area?.area
                  ? Colours.main : Colours.grey666666,
              ),
            ).tap(() {
              logic.area = e;
              if (e.list?.isNotEmpty ?? false) {
                logic.selectCountry = e.list?.first.country ?? "";
              }
            }),
          )) ?? []
        ],
      ),
    );
  }

  Widget _leftList() {
    return Container(
      width: 80,
      color: Colours.greyF5F7FA,
      child: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: ListView(
          controller: logic.leftController,
          children: [
            ...(logic.area?.list ?? []).map((ChannelCountryEntity e) {
              final selected = logic.selectCountry == e.country;
              return Container(
                color: selected ? Colors.white : null,
                height: 44,
                child: Row(
                  children: [
                    Container(
                      width: 3,
                      height: 24,
                      decoration: BoxDecoration(
                        color: selected ? Colours.main : null,
                        borderRadius: const BorderRadius.horizontal(
                          right: Radius.circular(3)
                        )
                      ),
                    ),
                    Expanded(
                      child: QkdText(
                        e.country ?? "",
                        maxLines: 2,
                        textAlign: TextAlign.center,
                        fontSize: 13,
                        color: selected ? Colours.main : Colours.text,
                      )
                    ),
                    const SizedBox(width: 3)
                  ],
                ),
              ).tap(() {
                logic.contentController.controller = logic.bodyController;
                final index = logic.area?.list?.indexOf(e) ?? -1;
                log("click left list $index");
                if (index < 0 || index >= (logic.area?.list?.length ?? 0)) {
                  return;}
                logic.selectCountry = e.country ?? "";
                logic.contentController.jumpTo(index: index,sliverContext: logic.listContext);
              });
            })
          ],
        ),
      ),
    );
  }

  Widget _contentList(ScrollPhysics physics) {
    final contentWidth = (Get.width - 80 - 16);
    const itemWidth = 36 + 18;
    const ratio = itemWidth / 75;
    final space = contentWidth - itemWidth * 4;
    log("content width = $contentWidth itemwidth = $itemWidth");
    return Container(
      padding: const EdgeInsets.all(8),
      color: Colors.white,
      child: CustomScrollView(
        physics: physics,
        slivers: [
          SliverList.builder(
              itemCount: logic.area?.list?.length ?? 0,
              itemBuilder: (context, index) {
                if(logic.listContext != context) {
                  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                    logic.listContext = context;
                  });
                }
                final ChannelCountryEntity country = (logic.area?.list?[index])!;
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      height: 38,
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      child: QkdText(
                        country.country ?? "",
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                      )
                    ),
                    MediaQuery.removePadding(
                      context: context,
                      removeTop: true,
                      child: GridView.builder(
                        itemCount: country.list?.length ?? 0,
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4,
                            crossAxisSpacing: space / 3,
                            childAspectRatio: ratio
                        ),
                        itemBuilder: (context, index) {
                          final channel = country.list?[index];
                          return channelItem(channel);
                        },
                      ).marginOnly(bottom: 10),
                    )
                  ],
                );
              }
          ),
          SliverToBoxAdapter(
            child: Container(height: 50)
          )
        ],
      )
    );
  }

  Widget channelItem(ChannelEntity? channel){
    double size = 36;
    return GestureDetector(
      onTap: () {
        Utils.onEvent(
          "data_match_event_view",
          params: {"event_id": channel?.channelId}
        );
        Get.toNamed(
        Routes.leagueDetail,
        arguments: channel?.channelId,
        parameters: {"type":"${logic.channelType}"}
      );
      },
      child: Column(
        children: [
          CachedNetworkImage(
            width: size,height: size,
            imageUrl: channel?.channelLogo ?? "",
            fit: BoxFit.cover,
            placeholder: (context, url) =>
                Styles.placeholderIcon(width: size, height: size),
            errorWidget: (context, url, error) => Image.asset(
              Utils.getImgPath("record_channel_icon.png"),
              width: size, height: size
            ),
          ),
          const SizedBox(height: 2),
          QkdText(
            channel?.channelName?? "",
            fontSize: 12,
            maxLines: 1,
          )
        ],
      ),
    );
  }

  Widget top(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: Get.width,
          color: Colours.greyF2F3F7,
          padding: const EdgeInsets.only(top: 10),
          child: Row(
            children: [
              Expanded(
                child: LadderTabBar(
                  key: ValueKey(widget.type),
                  tag: "${widget.type}",
                  tabs: logic.topTabs.map((e) => QkdText(e)).toList(),
                  selectLabelStyle: TabStyle(color: Colours.text),
                  labelStyle: TabStyle(color: Colours.grey99,weight: FontWeight.w600),
                  needEnd: false,scrollable: true,
                  keepSize: true,
                  initialIndex: logic.topIndex,
                  labelPadding: const EdgeInsets.symmetric(horizontal: 10),
                  onTap: (value) {
                    logic.topIndex = value;
                  },
                ),
              ),
              if(logic.topIndex == 1)
              Image.asset(
                Utils.getImgPath("msg_clear_all.png"),
                width: 20,color: Colours.grey99
              ).paddingOnly(right: 17).tap(() async{
                var result = await Get.dialog(
                    QkdDialog.alert("要清除最近访问吗？")
                );
                if(result == true) SpUtils.deleteMatchRecent(logic.channelType+1);
                update();
              })
            ],
          ),
        ),
        if(logic.topIndex == 0)...[
          recent(logic.recentChannels,0)
        ]else if(logic.topIndex == 1)...[
          recent(SpUtils.getMatchRecent(logic.channelType+1),1)
        ],
        Container(height: 8,color: Colours.greyF2F3F7)
      ],
    );
  }

  Widget recent(List<RecentChannelEntity>? list,int index){
    double width = (Get.width-44)/3;
    double height = 44;
    return LoadingWidget<bool>(
      isLoading: list == null,
      loading: shimmerRecent(),
      data: list?.length == 0,
      noData: NoDataWidget(
        height: 176,needPic: false,tip: "暂无${index == 0?"近期赛事":"最近访问"}",
      ),
      child: () => GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        padding: const EdgeInsets.all(12),
        crossAxisCount: 3,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        childAspectRatio: width/height,
        children: list?.map((e) => recentItem(e)).toList() ?? []
      ),
    );
  }

  Widget recentItem(RecentChannelEntity? entity){
    double size = 36;
    return GestureDetector(
      onTap: () => Get.toNamed(
        Routes.leagueDetail,
        arguments: entity?.id,
        parameters: {"type":"${logic.channelType}"}
      ),
      child: Container(
        padding: const EdgeInsets.all(4),
        height: 44,
        decoration: BoxDecoration(
          color: Colours.greyF2F3F7,
          borderRadius: BorderRadius.circular(4)
        ),
        child: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: QkdImage(
                imageUrl: entity?.logo, width: size, height: size,
                placeholder: Styles.placeholderIcon(width: size, height: size),
                errorWidget: Image.asset(
                  Utils.getImgPath("record_channel_icon.png"),
                  width: size, height: size
                ),
              ),
            ),
            Container(width: 4),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  QkdText(entity?.name ?? "", fontSize: 12,maxLines: 1),
                  if(entity?.num.hasValue == true)...[
                    Container(height: 2),
                    QkdText("今日${entity?.num ?? 0}场",
                      fontSize: 10,color: Colours.grey66
                    )
                  ]
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget shimmerArea(){
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        height: 44,
        child: Row(
          children: List<Widget>.generate(10,
            (index) => const ShimmerLoading(width: 60, height: 24)
          ).insertEvery(Container(width: 10)),
        ),
      ),
    );
  }

  Widget shimmerLeft(){
    return ShimmerLoading(
      width: 80,
      height: Get.height,
      direction: ShimmerDirection.ttb,
    );
  }

  Widget shimmerList(ScrollPhysics physics){
    final contentWidth = (Get.width - 80 - 16);
    const itemWidth = 36 + 18;
    const ratio = itemWidth / 75;
    final space = contentWidth - itemWidth * 4;
    return Container(
        padding: const EdgeInsets.all(8),
        color: Colors.white,
        child: CustomScrollView(
          physics: physics,
          slivers: [
            SliverList.builder(
                itemCount: 10,
                itemBuilder: (context, index) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                          height: 38,
                          alignment: Alignment.centerLeft,
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          child: const ShimmerLoading(width: 52,height: 17)
                      ),
                      MediaQuery.removePadding(
                        context: context,
                        removeTop: true,
                        child: GridView.builder(
                          itemCount: 8,
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4,
                            crossAxisSpacing: space / 3,
                            childAspectRatio: ratio
                          ),
                          itemBuilder: (context, index) => shimmerChannel(),
                        ).marginOnly(bottom: 10),
                      )
                    ],
                  );
                }
            ),
            SliverToBoxAdapter(
                child: Container(height: 50)
            )
          ],
        )
    );
  }

  Widget shimmerChannel(){
    return const Column(
      children: [
        ShimmerLoading(width: 36, height: 36),
        SizedBox(height: 2),
        ShimmerLoading(width: 36, height: 17)
      ],
    );
  }

  Widget shimmerRecent(){
    return GridView.count(
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      padding: const EdgeInsets.all(12),
      crossAxisCount: 3,
      mainAxisSpacing: 10,
      crossAxisSpacing: 10,
      childAspectRatio: (Get.width-44)/3/44,
      children: List.generate(9,
        (index) => const ShimmerLoading(width: 111, height: 44)
      )
    );
  }
}
